package edu.scut.yi.yx.processer;

import java.sql.SQLException;
import java.util.List;

import com.electrotank.electroserver5.entities.User;
import com.electrotank.electroserver5.extensions.api.PluginApi;
import com.electrotank.electroserver5.extensions.api.value.EsObject;
import com.electrotank.electroserver5.extensions.api.value.EsObjectRO;

import edu.scut.yi.yx.dbmanager.DatabaseJDBCPlugin;
import edu.scut.yi.yx.lobbymanager.Command;

public class AddBuddyProcesser extends AbstractProcesser{

	private DatabaseJDBCPlugin databaseJDBCPlugin;
	private EsObject addresponse;
	@Override
	public String getCommand() {
		// TODO Auto-generated method stub
		return Command.AddBuddy.getCode();
	}

	@Override
	public void process(String user, EsObjectRO message, PluginApi api) {
		// TODO Auto-generated method stub
		String buddy = message.getString(Command.Message.getCode());
		databaseJDBCPlugin = (DatabaseJDBCPlugin)api.getServerPlugin("DatabaseJDBCPlugin");
		if(api.isBuddy(user, buddy)){
			addresponse = new EsObject();
			addresponse.setString(Command.Action.getCode(), Command.AddBuddy.getCode());
			addresponse.setString(Command.State.getCode(), Command.Failed.getCode());
			addresponse.setString(Command.Message.getCode(), Command.IsBuddy.getCode());
		}else{
			api.addBuddy(user, buddy, null);
		try{
			boolean result = databaseJDBCPlugin.executeSQL("INSERT INTO buddylist VALUES ( '"+user+"','"+buddy+"')");
			
			if(result){
			addresponse = new EsObject();
			addresponse.setString(Command.Action.getCode(), Command.AddBuddy.getCode());
			addresponse.setString(Command.State.getCode(), Command.Success.getCode());
			}
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
			api.sendPluginMessageToUser(user, addresponse);
	}

}
